import FakeProgress from 'fake-progress'

const state = {
  show: false,          // 是否显示进度
  progress: 0,          // 当前进度（0-100）
  activeRequests: 0,    // 活跃请求数
  fakes: new Map()      // 存储每个请求的 FakeProgress 实例 { config.url: { instance, timer } }
}

const mutations = {
  ADD_REQUEST(state, url) {
    state.activeRequests++
    if (!state.show) state.show = true
  },
  REMOVE_REQUEST(state, url) {
    state.activeRequests = Math.max(0, state.activeRequests - 1)
    state.fakes.delete(url)
    if (state.activeRequests === 0) state.show = false
  },
  UPDATE_PROGRESS(state, progress) {
    state.progress = progress
  },
  ADD_FAKE(state, { url, instance, timer }) {
    state.fakes.set(url, { instance, timer })
  }
}

const actions = {
  // 启动请求进度
  start({ commit, state }, config) {
    const url = config.url
    commit('ADD_REQUEST', url)

    // 创建 FakeProgress 实例
    const fake = new FakeProgress({
      timeConstant: 5000, // 进度到达 63% 所需时间
      autoStart: false
    })

    // 进度更新定时器
    const timer = setInterval(() => {
      const allProgress = Array.from(state.fakes.values())
        .map(f => f.instance.progress)
        .reduce((a, b) => a + b, 0)
      
      const avgProgress = allProgress / state.fakes.size || 0
      commit('UPDATE_PROGRESS', Math.floor(avgProgress * 100))
    }, 200)

    fake.start()
    commit('ADD_FAKE', { url, instance: fake, timer })
  },

  // 完成请求
  end({ commit, state }, config) {
    const url = config.url
    const fake = state.fakes.get(url)
    if (fake) {
      fake.instance.end()
      clearInterval(fake.timer)
      commit('REMOVE_REQUEST', url)
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}